﻿using System;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;

namespace Microestc.EventBus.RabbitMQ
{
    public static class EventBusRabbitMQExtension
    {
        public static IServiceCollection AddEventBusRabbitMQ(this IServiceCollection services, IConfiguration configuration)
        {
            if (!configuration.GetSection("EventBusSettings").Exists()) throw new Exception("please configure EventBus Settings.");
            services.Configure<EventBusSettings>(configuration.GetSection("EventBusSettings"));
            services.AddLogging();

            services.AddSingleton<IRabbitMQPersistentConnection, DefaultRabbitMQPersistentConnection>();
            services.AddSingleton<IEventBusSubscriptionsManager, EventBusSubscriptionsManager>();
            services.AddSingleton<IEventBus, EventBusRabbitMQ>();

            return services;
        }


        public static IApplicationBuilder ConfigureEventBusRabbitMQ(this IApplicationBuilder app, Action<IEventBus> configure)
        {
            var eventBus = app.ApplicationServices.GetRequiredService<IEventBus>();
            if (eventBus == null) throw new Exception("please add EventBus services.");
            configure(eventBus);
            return app;
        }

        #region OLD
        //public static IApplicationBuilder AutoConfigureEventBusRabbitMQ(this IApplicationBuilder app)
        //{
        //    var eventBus = app.ApplicationServices.GetRequiredService<IEventBus>();
        //    var logger = app.ApplicationServices.GetRequiredService<ILogger<IEventBus>>();
        //    using (logger.BeginScope("EventBus Subscribe"))
        //    {
        //        logger.LogInformation($"=======================================================================");
        //        foreach (Type eType in typeof(IntegrationEvent).GetAssemblies())
        //        {
        //            foreach (Type hType in typeof(IIntegrationEventHandler<>).GetMakeGenericType(eType))
        //            {
        //                logger.LogInformation($"{eType.Name}\t=>\t{hType.Name}");
        //                eventBus.Subscribe(eType, hType);
        //            }
        //        }
        //        logger.LogInformation($"=======================================================================");
        //    }
        //    return app;
        //}
        #endregion
    }
}